package fr.gla.hibtracker.historique.listener;

import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.event.FlushEvent;
import org.hibernate.event.def.DefaultFlushEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.gla.hibtracker.historique.bm.FlushModifications;
import fr.gla.hibtracker.historique.bs.UserResolver;

@SuppressWarnings("serial")
public class FlushEventListener extends DefaultFlushEventListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(FlushEventListener.class);

    private UserResolver        userResolver;

    public FlushEventListener() {
        super();
        LOGGER.trace("Création d'un nouveau {}", getClass().getName());
    }


    public FlushEventListener(UserResolver userResolver) {
        this();
        this.userResolver = userResolver;
    }


    /**
     * @see org.hibernate.event.def.DefaultFlushEventListener#onFlush(org.hibernate.event.FlushEvent)
     */
    @Override
    public void onFlush(FlushEvent event) throws HibernateException {
        LOGGER.debug("Flush event ! Creation d'une nouvelle instance de FlushModifications et placement dans le ThreadLocal");
        FlushModifications flushModifications = new FlushModifications();
        flushModifications.setDateModification(new Date());
        flushModifications.setUser(resolveUser(event));
        FlushModificationThreadLocal.setFlushModifications(flushModifications);
        LOGGER.debug("Délégation à super.onFlush");
        super.onFlush(event);
        LOGGER.debug("Fin du flush event  : suppression des FlushModifications du thread local");
        FlushModificationThreadLocal.setFlushModifications(null);
    }

    private String resolveUser(FlushEvent entityEvent) {
        return (userResolver == null) ? null : userResolver.resolve(entityEvent);
    }

    public void setUserResolver(UserResolver userResolver) {
        this.userResolver = userResolver;
    }
}
